package dao;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;

import model.Endpoint;
import model.EndpointType;
import model.Field;
import model.Tile;
import model.Tile.Rotation;
import model.TileType;

public class FieldDao extends Dao {
	private static File TILE_TYPE_FOLDER = new File("resources/fields");
	
	private TileTypeDao tileTypeDao = new TileTypeDao();

	public static void main(String[] args) throws IOException {
		FieldDao dao = new FieldDao();
		Field field = dao.load("sample");
		
	}

	public Field load(String name) throws IOException {
		File file = new File(TILE_TYPE_FOLDER, name + ".data");
		if (file.exists() && file.canRead()) {
			Field type = load(file);
			return type;
		}
		return null;
	}

	private Field load(File file) throws IOException {
		FileReader reader = new FileReader(file);
		BufferedReader buffered = new BufferedReader(reader);
		int[] size = this.parseIntegerList(buffered.readLine());
		Tile[][] tiles = new Tile[size[0]][size[1]];
		for(int y = 0; y < size[1]; y++) {
			String[] tileline = buffered.readLine().split(",");
			for(int x = 0; x < tileline.length; x++) {
				tiles[x][y] = parseTile(tileline[x]);
			}
		}
		int endpointcount = parseInt(buffered.readLine());
		Endpoint[] endpoints = new Endpoint[endpointcount * 2];  
		for(int i = 0; i < endpointcount; i++) {
			int[] pointinformations = parseIntegerList(buffered.readLine());
			endpoints[i * 2] = new Endpoint(EndpointType.OUTPUT, pointinformations[0], pointinformations[1]);
			endpoints[i * 2 + 1] = new Endpoint(EndpointType.INPUT, pointinformations[0], pointinformations[2]);
		}
		Field field = new Field();
		field.setTiles(tiles);
		field.setEndpoints(endpoints);
		return field;
	}
	
	private Tile parseTile(String informations) throws IOException {
		int dot = informations.lastIndexOf('.');
		int rotation = parseInt(informations.substring(dot + 1));
		System.out.println(rotation);
		TileType type = tileTypeDao.load(informations.substring(0, dot));
		Tile tile = new Tile();
		tile.setType(type);
		switch(rotation) {
		case 0:
			tile.setRotation(Rotation.DEGREES_0);
			break;
		case 1:
			tile.setRotation(Rotation.DEGREES_90);
			break;
		case 2:
			tile.setRotation(Rotation.DEGREES_180);
			break;
		case 3:
			tile.setRotation(Rotation.DEGREES_270);
			break;
		}
		return tile;
	}
}
